package top.sjydzq.www.controller.Mall;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import top.sjydzq.www.bean.Cart;
import top.sjydzq.www.bean.CartItem;
import top.sjydzq.www.service.CartService;

import java.util.List;

@Controller
@RequestMapping("/cart/")
public class CartController {
    @Autowired
    private CartService cartService;
    @Autowired
    private Cart cart;

    @RequestMapping("index")
    public String index(int uid, Model model) {
        List<CartItem> cartItems = cartService.selectAll(uid);

        cart.setItems(cartItems);

        double totalMoney = 0;
        for (CartItem item: cartItems) {
            totalMoney += item.getSubtotal();
        }

        cart.setMoney(totalMoney);

        model.addAttribute("cart", cart);

        return "Mall/Cart/index";
    }

    @RequestMapping("add")
    public String add(int pid, int amount, int uid) {
        boolean status = cartService.add(pid, amount, uid);

        return String.format("redirect:/cart/addResult?status=%b&pid=%d", status, pid);
    }

    @RequestMapping("addResult")
    public String addResult(boolean status, int pid, Model model) {
        model.addAttribute("status", status);
        model.addAttribute("pid", pid);

        return "Mall/Cart/addResult";
    }

    @RequestMapping("changeAmount")
    public String changeAmount(int cid, int amount, int uid) {
        cartService.changeAmount(cid, amount, uid);

        return String.format("redirect:/cart/index?uid=%d", uid);
    }

    @RequestMapping("clear")
    public String clear(int uid) {
        cartService.clear(uid);

        return String.format("redirect:/cart/index?uid=%d", uid);
    }

    @RequestMapping("remove")
    public String remove(int cid, int uid) {
        cartService.deleteById(cid, uid);

        return String.format("redirect:/cart/index?uid=%d", uid);
    }
}
